package emu.decvices.save;

import emu.EMU;

import java.io.*;

/**
 * 存档处理器
 */
public class SaveHandler {
    public static final String SAVE_FILE_EXT = ".sav";
    public static final String QUICK_SAVE_FILE_EXT = ".qsav";
    public static void save(String fileName,byte[] data){
        File saveFile = new File(EMU.DEFAULT_SAVE_PATH,getFileName(fileName) + SAVE_FILE_EXT);
        try (
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
         ){
            fileOutputStream.write(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static byte[] load(String fileName){
        byte[] data = new byte[0];
        File saveFile = new File(EMU.DEFAULT_SAVE_PATH,getFileName(fileName) + SAVE_FILE_EXT);
        if(saveFile.exists()){
            try {
                data = new byte[(int)saveFile.length()];
                FileInputStream fileInputStream = new FileInputStream(saveFile);
                fileInputStream.read(data);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return data;
    }

    public static void quickSave(String fileName,Save save){
        File saveFile = new File(EMU.DEFAULT_QUICK_SAVE_PATH,getFileName(fileName) + QUICK_SAVE_FILE_EXT);
        try (
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
                ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
        ){
            oos.writeObject(save);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 是否可以即时读档
     * @param fileName
     * @return
     */
    public static boolean quickLoadEnable(String fileName){
        //存在存档文件即可
        File saveFile = new File(EMU.DEFAULT_QUICK_SAVE_PATH,getFileName(fileName) + QUICK_SAVE_FILE_EXT);
        return saveFile.exists();
    }
    public static Save quickLoad(String fileName){
        File saveFile = new File(EMU.DEFAULT_QUICK_SAVE_PATH,getFileName(fileName) + QUICK_SAVE_FILE_EXT);
        try (
                FileInputStream fileInputStream = new FileInputStream(saveFile);
                ObjectInputStream ois = new ObjectInputStream(fileInputStream);
        ){
            return (Save)ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    private static String getFileName(String fileName){
        if(fileName.toLowerCase().endsWith(".nes")){
            fileName = fileName.substring(0,fileName.lastIndexOf("."));
        }
        return fileName;
    }
}
